package com.zhangfb95.crosschain.console.command;

import com.fasterxml.jackson.core.type.TypeReference;
import com.zhangfb95.crosschain.console.enums.CommandEnum;
import com.zhangfb95.crosschain.infra.model.Result;
import com.zhangfb95.crosschain.infra.util.json.JsonUtil;
import com.zhangfb95.crosschain.sdk.CrossChainClient;
import com.zhangfb95.crosschain.sdk.infra.model.api.request.server.rpcchain.RpcSendApiReq;
import com.zhangfb95.crosschain.sdk.infra.model.api.response.server.rpcchain.RpcSendApiRes;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author zhangfubing
 * @since 2023/12/21
 */
@Component
public class SendCommand implements Command {

    @Autowired
    private CrossChainClient crossChainClient;
    @Autowired
    private JsonUtil jsonUtil;

    @Override
    public CommandEnum command() {
        return CommandEnum.SEND;
    }

    @Override
    public boolean handle(String[] args) {
        if (args.length < 2 || isHelp(args)) {
            System.out.println("Usage: send [path] [method] [args...]");
            return false;
        }

        String path = args[0];
        String method = args[1];
        String arg = args[2];
        String[] sendArgs = jsonUtil.readValue(arg, new TypeReference<>() {
        });

        RpcSendApiReq apiReq = new RpcSendApiReq()
                .setChainPath(path)
                .setMethod(method)
                .setArgs(sendArgs);
        Result<RpcSendApiRes> apiRes = crossChainClient.send(apiReq);
        if (apiRes.isSuccess()) {
            System.out.println("TxID  : " + apiRes.getData().getTransactionID());
            System.out.println("Result: " + apiRes.getData().getResult());
        } else {
            System.out.println("Result: " + apiRes.getMsg());
        }
        return false;
    }
}
